package com.house365.im.client.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

import com.house365.im.client.IMManager;
import com.house365.im.client.util.LogUtil;
import com.house365.im.client.util.NetworkUtil;

/**
 * @author py
 * @date 2013-2-21
 * @comment
 */
public class HeartbeatReceiver extends BroadcastReceiver {
	private static final String LOGTAG = LogUtil
			.makeLogTag(HeartbeatReceiver.class);
	private WakeLock wakeLock;

	public static final int WAKE_LOCK_OPEN = 1;
	public static final int WAKE_LOCK_CLOSE = 2;
	private Context context;
	private Handler wakeLockHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == WAKE_LOCK_OPEN) {
				acquireWakeLock();
			} else if (msg.what == WAKE_LOCK_CLOSE) {
				releaseWakeLock();
			}
		}
	};

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		Log.i(LOGTAG, "HeartbeatReceiver.onReceive...action:"+intent.getAction());
		// 获取电源控制，防止在心跳注册的时间内，cpu停止
		// wakeLockHandler.sendEmptyMessage(WAKE_LOCK_OPEN);
		acquireWakeLock();
	
		if (NetworkUtil.isNetworkAvailable(context)) {
			new Thread() {
				public void run() {
					if(	IMManager.getIMManager().isConnected()){
						boolean isSuccess = 	IMManager.getIMManager().sendHeartBeatPkg();
						Log.i(LOGTAG, "HeartbeatReceiver.sendHeartBeatPkg..."+isSuccess);
						if(!isSuccess){
							IMManager.getIMManager().login(true);
						}
					}else{
						Log.i(LOGTAG, "HeartbeatReceiver.login...");
						IMManager.getIMManager().login(false);
					}
				};

			}.start();
		} else {
			Log.i(LOGTAG,
					"HeartbeatReceiver. Network  Is UnAvailable...,re heart—beat at next min");
		}
		releaseWakeLock();
		// 如果10秒钟还没连接上，直接放弃
		// wakeLockHandler.sendEmptyMessageDelayed(WAKE_LOCK_CLOSE,10000);

	}

	public void releaseWakeLock() {
		if (wakeLock != null && wakeLock.isHeld()) {
			wakeLock.release();
			wakeLock = null;
		}
	}

	public void acquireWakeLock() {

		if (wakeLock == null) {
			PowerManager pm = (PowerManager) context
					.getSystemService(Context.POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
					.getClass().getCanonicalName());
			wakeLock.acquire();
		}
	}
}
